package com.teamclub.app.sservices.systemmanager

import io.ebean.{Ebean, ExpressionList}
import com.fasterxml.jackson.databind.JsonNode
import com.teamclub.app.sforms.AppRoleForm
import com.teamclub.domain.system.AppRole
import com.teamclub.util.errors.ErrorCode
import com.teamclub.util.libs.F
import com.teamclub.util.page.Pager
import org.apache.commons.lang3.StringUtils
import org.springframework.beans.BeanUtils
import org.springframework.stereotype.Service

/**
  * Created by ilkkzm on 17-8-11.
  */

@Service
class AppRoleService {
  def expr(where: ExpressionList[AppRole], form: AppRoleForm) = {
    if(form.id != null) {
      where.eq("id", form.id)
    }
    if(StringUtils.isNotBlank(form.name)) {
      where.eq("name", form.name)
    }
    if(StringUtils.isNotBlank(form.organNo)){
      where.eq("organNo", form.organNo)
    }
  }

  def list(form: AppRoleForm): F.Either[JsonNode, ErrorCode] =  {
    var where = Ebean.find(classOf[AppRole]).where()
    expr(where, form)
    F.Either.Left(Pager.genePagerJson(where.query(), form))
  }

  def add(form: AppRoleForm): F.Either[AppRole, ErrorCode] = {
    var appRole = new AppRole
    if(form.id != null) {
      appRole = Ebean.find(classOf[AppRole], form.id)
    }
    if(appRole == null) {
      F.Either.Right(ErrorCode.ENTITY_NOT_FOUND)
    } else {
      BeanUtils.copyProperties(form, appRole)
      if(form.id == null) {
        appRole.save()
      } else {
        appRole.update()
      }
      F.Either.Left(appRole)
    }
  }

  def del(form: AppRoleForm): F.Either[AppRole, ErrorCode] = {
    val appRole = Ebean.find(classOf[AppRole], form.id)
    if(appRole == null) {
      F.Either.Right(ErrorCode.ENTITY_NOT_FOUND)
    } else {
      appRole.delete()
      F.Either.Left(appRole)
    }
  }
}
